package com.jsp.study.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class Batch {

	public Connection getConnection() {
		Connection conn = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			String url = "jdbc:mysql://118.89.160.58:3306/xbin_db?relaxAutoCommit=true&useUnicode=true&characterEncoding=UTF-8&characterSetResults=UTF-8&zeroDateTimeBehavior=convertToNull&autoReconnect=true&failOverReadOnly=false";
			conn = DriverManager.getConnection(url, "xbin", "xbin0629");
		} catch (Exception e) {
			System.out.println("数据库连接失败");
		}
		return conn;
	}
	
	public int saveBatch() {
		int row = 0;
		Connection conn = getConnection();
		if (conn != null) {
			PreparedStatement ps = null;
			try {
				String sql = "insert into tb_books(name, price, bookcount, author) values (?, ?, ?, ?)";
				ps = conn.prepareStatement(sql);
				conn.setAutoCommit(false);
				for (int i = 1; i < 8; i++) {
					ps.setString(1, "书本" + i);
					ps.setDouble(2, Double.parseDouble("99." + i));
					ps.setInt(3, Integer.parseInt("100" + i));
					ps.setString(4, "作者" + i);
					ps.addBatch();
				}
				int[] rows = ps.executeBatch();
				conn.commit();
				row = rows.length;
				ps.close();
				conn.close();
			} catch (Exception e) {
				System.out.println("执行数据库过程中异常");
			}
		}
		return row;
	}
	
	
}
